package com.itheima.reggie.controller;

import ch.qos.logback.classic.turbo.MarkerFilter;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description: hamo
 * @Create by: 渭北彭于晏
 * @Date: 2021/11/3 10:53
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${savepath}")
    private String savepath;

    @PostMapping("/upload")
    public R shangchuan(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//获取文件名
        String h = FilenameUtils.getExtension(originalFilename);//获取该文件得后缀名
        String uuid = UUID.randomUUID().toString();//生成随机32位的字符串
        String result =  uuid + "." + h;
        file.transferTo(new File(savepath + result));
        return R.success(result);
    }

    @GetMapping("/download")
    public R xiazai(String name, HttpServletResponse response) throws IOException {
        FileInputStream fis = new FileInputStream(new File(savepath,name));
        IOUtils.copy(fis, response.getOutputStream());
        return R.success("成功");
    }
}
